package main

import (
	"fmt"
	"time"
	influx "github.com/influxdata/influxdb/client/v2"
)

func main(){
	conf := influx.HTTPConfig{
		Addr:     "http://10.20.0.10:8086",
		Username: "root",
		Password: "123qwe",
		Timeout:  5 * time.Second,
	}
	c, err := influx.NewHTTPClient(conf)
	if err != nil{
		return
	}
	//查询所有的CQ
	cqMap := make(map[string]struct{})
	query := influx.NewQuery("SHOW CONTINUOUS QUERIES", "prometheus", "ms")

	res, err := c.Query(query)
	ss := res.Results[0].Series
	for _, s := range ss{
		if s.Name == "prometheus"{
			for _, v := range s.Values{
				cq := v[0].(string)
				cqMap[cq] = struct{}{}
			}

		} else{
			continue
		}
	}
	fmt.Println(1111, cqMap)
	//查出所有的measurement
	query = influx.NewQuery("show measurements", "prometheus", "ms")
	res, err = c.Query(query)
	ss = res.Results[0].Series
	for _, s := range ss{
		for _, v := range s.Values{
			metric := v[0].(string)
			//查询该metric有没有对应的cq
			cq := fmt.Sprintf("cq_rp_2d_%s", metric)
			if _, ok := cqMap[cq]; !ok{
				// 创建cq
				command := fmt.Sprintf("CREATE CONTINUOUS QUERY cq_rp_2d_%s ON prometheus " +
					"BEGIN SELECT mean(value) as value INTO prometheus.rp_2d.%s FROM prometheus.autogen.%s " +
					"GROUP BY time(5m), * END", metric, metric, metric)
				fmt.Println(222, command)
				query := influx.NewQuery(command, "prometheus", "ms")
				res, err = c.Query(query)
				fmt.Println(res, err)
			}

			cq = fmt.Sprintf("cq_rp_7d_%s", metric)
			if _, ok := cqMap[cq]; !ok{
				// 创建cq
				command := fmt.Sprintf("CREATE CONTINUOUS QUERY cq_rp_7d_%s ON prometheus " +
					"BEGIN SELECT mean(value) as value INTO prometheus.rp_7d.%s FROM prometheus.autogen.%s " +
					"GROUP BY time(20m), * END", metric, metric, metric)
				query := influx.NewQuery(command, "prometheus", "ms")
				res, err = c.Query(query)
				fmt.Println(res, err)
			}

			cq = fmt.Sprintf("cq_rp_3m_%s", metric)
			if _, ok := cqMap[cq]; !ok{
				// 创建cq
				command := fmt.Sprintf("CREATE CONTINUOUS QUERY cq_rp_3m_%s ON prometheus " +
					"BEGIN SELECT mean(value) as value INTO prometheus.rp_3m.%s FROM prometheus.autogen.%s " +
					"GROUP BY time(3h), * END", metric, metric, metric)
				query := influx.NewQuery(command, "prometheus", "ms")
				res, err = c.Query(query)
				fmt.Println(res, err)
			}

			cq = fmt.Sprintf("cq_rp_1y_%s", metric)
			if _, ok := cqMap[cq]; !ok{
				// 创建cq
				command := fmt.Sprintf("CREATE CONTINUOUS QUERY cq_rp_1y_%s ON prometheus " +
					"BEGIN SELECT mean(value) as value INTO prometheus.rp_1y.%s FROM prometheus.autogen.%s " +
					"GROUP BY time(12h), * END", metric, metric, metric)
				query := influx.NewQuery(command, "prometheus", "ms")
				res, err = c.Query(query)
				fmt.Println(res, err)
			}
		}
	}

}



